package com.xiaotu.spider.downloader;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHost;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.util.MathUtil;
import com.xiaotu.common.util.PropertiesUtil;

import us.codecraft.webmagic.proxy.Proxy;
import us.codecraft.webmagic.proxy.SimpleProxyPool;

/**
 * @类名 AliyunProxyPool
 * @日期 2017年3月9日
 * @作者 高海军
 * @功能 阿里云的代理
 */
public class AliyunProxyPool extends SimpleProxyPool
{
	
	public static final String ALIYUN_PROXY = "proxy.aliyun";
	
	public AliyunProxyPool()
	{
		super(null, false);
		
		String proxy = PropertiesUtil.getProperty(ALIYUN_PROXY);
		if (StringUtils.isEmpty(proxy))
			throw new SpiderException(
					SpiderExceptionCode.DataInvalideException);
		String[] proxyArr = proxy.split(";");
		if (proxyArr == null || proxyArr.length < 1)
			throw new SpiderException(
					SpiderExceptionCode.DataInvalideException);
		String[][] proxyList = new String[proxyArr.length][];
		
		int i = 0;
		for (String proxyStr : proxyArr)
		{
			String[] oneProxyArr = proxyStr.split("\\|");
			if (oneProxyArr == null || oneProxyArr.length != 4)
				throw new SpiderException(
						SpiderExceptionCode.DataInvalideException);
			proxyList[i++] = oneProxyArr;
		}
		
		this.addProxy(proxyList);
	}
	
	@Override
	public Proxy getProxy()
	{
		int poolSize = this.getIdleNum();
		if (MathUtil.getRand(0, poolSize + 1) == poolSize)
			return null;
		return super.getProxy();
	}
	
	@Override
	public void returnProxy(HttpHost host, int statusCode)
	{
		if (host == null)// 说明未走代理
			return;
		if (statusCode != Proxy.SUCCESS && statusCode != Proxy.ERROR_403)
			statusCode = Proxy.SUCCESS;
		super.returnProxy(host, statusCode);
	}
}
